package com.mxx.common.data.mongo;

import com.mxx.common.conv.BeanUtil;
import com.mxx.common.conv.JacksonConverter;
import com.mxx.common.data.utils.MongoUtil;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Optional;

/**
 * @Author itzgyw
 * @Date 2020-01-28
 * @Time 21:47
 * @Description:
 */
public class CustomMongoDBRepositoryIml<T, ID> extends SimpleMongoRepository<T, ID> implements CustomMongoDBRepository<T, ID> {
    private final MongoEntityInformation<T, ID> entityInformation;
    private final MongoOperations mongoOperations;
    private final String idName;
    private final Class<T> domainClass;
    private JacksonConverter jacksonConverter;

    public CustomMongoDBRepositoryIml(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
        super(metadata, mongoOperations);
        this.jacksonConverter = JacksonConverter.getInstance();
        this.entityInformation = metadata;
        this.mongoOperations = mongoOperations;
        this.idName = entityInformation.getIdAttribute();
        this.domainClass = entityInformation.getJavaType();
    }

    @Override
    public boolean updateById(T entity) {
        Assert.notNull(entity, "entity must not be null!");
        ID id = entityInformation.getId(entity);
        if (id == null) {
            return false;
        }
        Query query = Query.query(Criteria.where("_id").is(id));
        Update update = MongoUtil.getUpdate();
        BeanUtil.eachObject(entity, (k, v) -> {
            if (idName.equals(k)) {
                return;
            }
            if (v != null) {
                update.set(k, v);
            }
        });

        return mongoOperations.update(domainClass).matching(query).apply(update).first().getModifiedCount() == 1;
    }

    @Override
    public boolean updateById(Document document) {
        Object id = document.get(idName);
        Assert.notNull(id, "entity must not be null!");
        if (id instanceof ObjectId) {
            document.put(idName, id.toString());
        }
        T entity = jacksonConverter.convertValue(document, domainClass);
        return updateById(entity);
    }

    @Override
    public long count(Query query) {
        return mongoOperations.count(query, domainClass);
    }

    @Override
    public long updateMulti(Query query, Update update) {
        Assert.notNull(query, "Query must not be null!");
        Assert.notNull(query, "Update must not be null!");
        return mongoOperations.update(domainClass).matching(query).apply(update).all().getModifiedCount();
    }

    @Override
    public List<T> findAll(Query query) {
        Assert.notNull(query, "Query must not be null!");
        Assert.notNull(query, "voClass must not be null!");
        return mongoOperations.find(query, domainClass);
    }

    @Override
    public Page<T> findPage(Query query, Pageable pageable) {
        Assert.notNull(pageable, "Pageable must not be null!");
        Assert.notNull(query, "Pageable must not be null!");
        Long count = this.count(query);
        List<T> list = mongoOperations.find(query.with(pageable), domainClass);
        return new PageImpl(list, pageable, count);
    }

    @Override
    public Page<T> findPage(Pageable pageable) {
        return findPage(new Query(), pageable);
    }

    @Override
    public long delete(Query query) {
        Assert.notNull(query, "Pageable must not be null!");
        return mongoOperations.remove(domainClass).matching(query).all().getDeletedCount();
    }

    @Override
    public Optional<T> findOne(Query query) {
        T entity = mongoOperations.findOne(query, domainClass);
        return Optional.ofNullable(entity);
    }


    @Override
    public Class<T> getDomainClass() {
        return domainClass;
    }
}
